package kr.or.kead.module;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JComboBox;

import java.awt.Font;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.swing.SwingConstants;

@SuppressWarnings("serial")
public class RegEmail extends JPanel {
	private JTextField txtFirstDomain;
	private JLabel lblNewLabel;
	private JComboBox<String> comboBox;
	private JTextField txtSecondDomain;
	private final String[]  MAIL_SITE = {
			"hanmail.net","naver.com","gmail.com",
			"korea.com","nate.com","yahoo.com"
	};
	
	public RegEmail() {
		initialize();
	}
		
	public String getEmail() {
		return txtFirstDomain.getText() + "@" + txtSecondDomain.getText();
	}
	
	public void setEmail(String email) {
		StringTokenizer str = new StringTokenizer(email, "@");
		txtFirstDomain.setText(str.nextToken());
		txtSecondDomain.setText(str.nextToken());
	}

	private void initialize() {
		setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
		
		txtFirstDomain = new JTextField();
		txtFirstDomain.setHorizontalAlignment(SwingConstants.CENTER);
		txtFirstDomain.setFont(new Font("궁서체", Font.BOLD, 12));
		add(txtFirstDomain);
		txtFirstDomain.setColumns(10);
		
		lblNewLabel = new JLabel("@");
		lblNewLabel.setFont(new Font("궁서체", Font.BOLD, 12));
		add(lblNewLabel);
		
		txtSecondDomain = new JTextField();
		txtSecondDomain.setHorizontalAlignment(SwingConstants.CENTER);
		txtSecondDomain.setFont(new Font("궁서체", Font.BOLD, 12));
		txtSecondDomain.setText("직접입력");		
		add(txtSecondDomain);
		txtSecondDomain.setColumns(10);
		txtSecondDomain.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {		
				super.mouseClicked(e);
				txtSecondDomain.selectAll();
			}
			
		});
		
		txtSecondDomain.addFocusListener(new FocusAdapter() {
			public void focusLost(FocusEvent e) {
				super.focusLost(e);
				if(Pattern.matches("^[a-z]{1,9}.com||"
						+ "[a-z]{1,9}.net||[a-z]{1,9}.org||[a-z]{1,9}.co.kr$", 					
						txtSecondDomain.getText().toLowerCase()) == false) {
					JOptionPane.showMessageDialog(null, "이메일 입력이 잘못되었습니다");					
					txtSecondDomain.selectAll();
				}
			}
			
		});
		
		comboBox = new JComboBox<>(MAIL_SITE);
		comboBox.setFont(new Font("궁서체", Font.BOLD, 12));
		comboBox.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				txtSecondDomain.setText((String)comboBox.getSelectedItem());
				txtSecondDomain.updateUI();
			}
		});
		add(comboBox);
	}

}
